<template>
  <div class="permit-list">
    <div class="page-container">
      <div class="page-header">
        <h2>申请列表</h2>
        <el-button type="primary" @click="goToApply">
          <el-icon><Plus /></el-icon>
          新建申请
        </el-button>
      </div>

      <!-- 搜索筛选 -->
      <el-card class="search-card">
        <el-form :model="searchForm" inline>
          <el-form-item label="许可证号">
            <el-input
              v-model="searchForm.permitNumber"
              placeholder="请输入许可证号"
              clearable
            />
          </el-form-item>
          <el-form-item label="工作类型">
            <el-select
              v-model="searchForm.workType"
              placeholder="请选择工作类型"
              clearable
            >
              <el-option label="高空作业" value="high_altitude" />
              <el-option label="动火作业" value="hot_work" />
              <el-option label="电气作业" value="electrical" />
              <el-option label="受限空间" value="confined_space" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option label="待审批" value="pending" />
              <el-option label="已通过" value="approved" />
              <el-option label="已拒绝" value="rejected" />
              <el-option label="执行中" value="executing" />
              <el-option label="已完成" value="completed" />
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 数据表格 -->
      <el-card class="table-card">
        <el-table
          v-loading="loading"
          :data="tableData"
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="permitNumber" label="许可证号" width="150" />
          <el-table-column prop="workType" label="工作类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getWorkTypeTagType(row.workType)">
                {{ getWorkTypeText(row.workType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="location" label="作业地点" min-width="150" />
          <el-table-column prop="applicant" label="申请人" width="100" />
          <el-table-column prop="applyTime" label="申请时间" width="150" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="currentApprover" label="当前审批人" width="100" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="text" @click="handleView(row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button
                v-if="row.status === 'pending'"
                type="text"
                @click="handleRevoke(row)"
              >
                <el-icon><Close /></el-icon>
                撤销
              </el-button>
              <el-button
                v-if="row.status === 'approved'"
                type="text"
                @click="handleExecute(row)"
              >
                <el-icon><Operation /></el-icon>
                执行
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

interface SearchForm {
  permitNumber: string
  workType: string
  status: string
  dateRange: string[]
}

interface PermitItem {
  id: number
  permitNumber: string
  workType: string
  location: string
  applicant: string
  applyTime: string
  status: string
  currentApprover: string
}

const router = useRouter()

const loading = ref(false)
const selectedRows = ref<PermitItem[]>([])

const searchForm = reactive<SearchForm>({
  permitNumber: '',
  workType: '',
  status: '',
  dateRange: []
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const tableData = ref<PermitItem[]>([])

// 获取工作类型标签类型
const getWorkTypeTagType = (type: string) => {
  const typeMap = {
    high_altitude: 'danger',
    hot_work: 'warning',
    electrical: 'info',
    confined_space: 'success'
  }
  return typeMap[type as keyof typeof typeMap] || 'info'
}

// 获取工作类型文本
const getWorkTypeText = (type: string) => {
  const textMap = {
    high_altitude: '高空作业',
    hot_work: '动火作业',
    electrical: '电气作业',
    confined_space: '受限空间'
  }
  return textMap[type as keyof typeof textMap] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    executing: 'info',
    completed: 'success'
  }
  return typeMap[status as keyof typeof typeMap] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    pending: '待审批',
    approved: '已通过',
    rejected: '已拒绝',
    executing: '执行中',
    completed: '已完成'
  }
  return textMap[status as keyof typeof textMap] || status
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    setTimeout(() => {
      tableData.value = [
        {
          id: 1,
          permitNumber: 'WP202501001',
          workType: 'high_altitude',
          location: 'A区3楼外墙',
          applicant: '张三',
          applyTime: '2025-01-15 09:30',
          status: 'pending',
          currentApprover: '李四'
        },
        {
          id: 2,
          permitNumber: 'WP202501002',
          workType: 'hot_work',
          location: 'B区1楼管道',
          applicant: '王五',
          applyTime: '2025-01-15 10:15',
          status: 'approved',
          currentApprover: '-'
        },
        {
          id: 3,
          permitNumber: 'WP202501003',
          workType: 'electrical',
          location: 'C区配电室',
          applicant: '赵六',
          applyTime: '2025-01-15 11:00',
          status: 'executing',
          currentApprover: '-'
        }
      ]
      pagination.total = 3
      loading.value = false
    }, 500)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    permitNumber: '',
    workType: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 选择变化
const handleSelectionChange = (selection: PermitItem[]) => {
  selectedRows.value = selection
}

// 查看详情
const handleView = (row: PermitItem) => {
  router.push(`/permit/detail/${row.id}`)
}

// 撤销申请
const handleRevoke = async (row: PermitItem) => {
  try {
    await ElMessageBox.confirm('确定要撤销该申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    ElMessage.success('撤销成功')
    fetchData()
  } catch {
    // 用户取消
  }
}

// 执行作业
const handleExecute = (row: PermitItem) => {
  router.push(`/permit/execution/${row.id}`)
}

// 跳转到申请页面
const goToApply = () => {
  router.push('/permit/apply')
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchData()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.permit-list {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #333;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
}
</style>
